package com.nzy.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.page.PageMethod;
import com.nzy.common.ResultData;
import com.nzy.controller.request.StockRequest;
import com.nzy.entity.Stock;
import com.nzy.service.StockService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 库存操作
 */
@RestController
@RequestMapping("/stock")
public class StockController {

    @Resource
    private StockService stockService;

    /**
     * 扣减库存
     */
    @RequestMapping(value = "/subtract", method = RequestMethod.POST)
    public ResultData subtract(StockRequest stockRequest){
       Stock stock = stockService.queryBySkuId(stockRequest.getSkuId());
       if(stock == null || stock.getStock() < 1){
           return ResultData.fail("商品不存在或库存为0");
       }
        Stock subStock = new Stock();
                BeanUtils.copyProperties(stockRequest, subStock);
        subStock.setId(stock.getId());
       stockService.subStock(subStock);
        return ResultData.success();
    }
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResultData create(StockRequest stockRequest){
        Stock stock = stockService.queryBySkuId(stockRequest.getSkuId());
        if(stock != null ){
            return ResultData.fail("商品已存在");
        }
        Stock newStock = new Stock();
        BeanUtils.copyProperties(stockRequest, newStock);
        stockService.insert(newStock);
        return ResultData.success();
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultData add(StockRequest stockRequest){
        Stock stock = stockService.queryBySkuId(stockRequest.getSkuId());
        if(stock == null ){
            return ResultData.fail("商品不存在");
        }
        Stock newStock = new Stock();
        BeanUtils.copyProperties(stockRequest, newStock);
        newStock.setId(stock.getId());
        stockService.addStock(newStock);
        return ResultData.success();
    }

    @RequestMapping(value = "query", method = RequestMethod.GET)
    public ResultData query(String skuId){
        Stock stock = stockService.queryBySkuId(skuId);
        if(stock == null ){
            return ResultData.fail("商品不存在");
        }
        return ResultData.success(stock);
    }

    @RequestMapping(value = "queryStock", method = RequestMethod.GET)
    public ResultData queryStock(String skuId){
        Stock stock = stockService.queryBySkuId(skuId);
        if(stock == null ){
            return ResultData.fail("商品不存在");
        }
        return ResultData.success(stockService.queryNumBySkuId(skuId));
    }
}
